package com.weilf.zookeeper.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * zookeeper 中所有的回调包装
 * @author weil-f
 * @date 2021/2/7 8:34
 */
@Slf4j
public class WatcherCallBack implements Watcher, AsyncCallback.StatCallback, AsyncCallback.DataCallback {

	private ZooKeeper zk;

	private MyConfig myConfig;

	private CountDownLatch cc  = new CountDownLatch(1);


	public void setMyConfig(MyConfig myConfig) {
		this.myConfig = myConfig;
	}

	public void setZk(ZooKeeper zk) {
		this.zk = zk;
	}

	public void awit(){
		zk.exists("/appConfig",this,this,"abc");
		try {
			cc.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 这个方法是节点的回调函数
	 * @param watchedEvent
	 */
	public void process(WatchedEvent watchedEvent) {
		switch (watchedEvent.getType()) {
			case None:
				break;
			case NodeCreated:
				log.info("节点创建了");
				zk.getData("/appConfig",this,this,"def");
				break;
			case NodeDeleted:
				log.info("节点删除了");
				myConfig.setConfig("");
				cc = new CountDownLatch(1);
				break;
			case NodeDataChanged:
				log.info("节点更新了");
				zk.getData("/appConfig",this,this,"def");
				break;
			case NodeChildrenChanged:
				// 子节点发生变化时的监听
				break;
		}
	}


	/**
	 * 这个也是回调
	 * @param rc
	 * @param path 路径
	 * @param ctx 上下文对象
	 * @param stat 数据
	 */
	public void processResult(int rc, String path, Object ctx, Stat stat) {
		if(rc != 0 && path != null){
			log.info("【判断存在的回调参数】rc===>{},path==={}",rc,path);
		}
		if(null != ctx){
			log.info("【判断存在的回调参数】ctx===>{}",ctx.toString());
		}

		if(stat != null){
			log.info("【判断存在的回调参数】stat===>{}",stat.toString());
			zk.getData("/appConfig",this,this,"bcd");
		}
	}

	/**
	 * 获取数据的回调
	 * @param rc
	 * @param path 路径
	 * @param ctx
	 * @param data 数据
	 * @param stat
	 */
	public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
		if(rc != 0 && path != null){
			log.info("【获取数据的回调参数】rc ===>{},path ===>{}",rc,path);
		}
		if(null != stat){
			log.info("【获取数据的回调参数】stat===>{}",stat.toString());
		}

		if(data != null){
			myConfig.setConfig(new String(data));
			cc.countDown();
		}
	}
}
